package com.mini.framework.db.mybatis;

import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.util.ReflectionUtils;

@SuppressWarnings("unchecked")
public class MybatisDao extends SqlSessionDaoSupport {

	public <T> Page<T> selectPage(String statementName,Object parameter,int pageNo,int pageSize) {
		String countStatementName = statementName + "_count";
		return selectPage(statementName, countStatementName, parameter,pageNo,pageSize);
	}

	public <T> Page<T> selectPage(String statementName, String countStatementName, Object parameter,int pageNo,int pageSize) {
		Page page = new Page(pageNo,pageSize);
		Number totalItems = (Number) getSqlSession().selectOne(countStatementName, parameter);
		if (totalItems != null && totalItems.longValue() > 0) {
			List list = getSqlSession().selectList(statementName,toParameterMap(parameter, page));
			page.setResult(list);
			page.setTotalItems(totalItems.longValue());
		}
		return page;
	}

	protected static Map toParameterMap(Object parameter, Page p) {
		Map map = toParameterMap(parameter);
		map.put("startRow", p.getStartRow());
		map.put("endRow", p.getEndRow());
		map.put("offset", p.getOffset());
		map.put("limit", p.getPageSize());
		return map;
	}

	protected static Map toParameterMap(Object parameter) {
		if (parameter instanceof Map) {
			return (Map) parameter;
		} else {
			try {
				return PropertyUtils.describe(parameter);
			} catch (Exception e) {
				ReflectionUtils.handleReflectionException(e);
				return null;
			}
		}
	}

}
